package cn.hnbjx.prepaid.common;


import cn.hnbjx.prepaid.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * 此注解修饰的类为一个全局异常处理类
 * 当控制层出现异常时:
 * 1)首先检测当前controller是否有异常处理方法
 * 2)其次检测全局异常处理类是否有异常处理方法
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseEntity<?> handlerBusinessException(Exception ex) {
        Result error = new Result();

        // 业务异常
        if (ex instanceof BusinessException) {
            error.setCode(((BusinessException) ex).getCode());
            error.setMsg(ex.getMessage());
            log.warn("[全局业务异常] 业务编码：{} 异常记录：{}", error.getCode(), error.getMsg());
        }

        // 未知错误
        else {
            error.setCode(BusinessStatus.UNKNOWN.getCode());
            error.setMsg(BusinessStatus.UNKNOWN.getMessage());
        }

        return new ResponseEntity<>(error, HttpStatus.OK);
    }

    /**
     * 空指针异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    public ResponseEntity<?> handleNullPointerException(Exception ex) {
        Result error = new Result();
        // 异常
        error.setCode(BusinessStatus.UNKNOWN.getCode());
        error.setMsg(ex.getMessage());
        log.warn("[空指针异常] 业务编码：{} 异常记录：{}", error.getCode(), error.getMsg());
        ex.printStackTrace();
        return new ResponseEntity<>(error, HttpStatus.OK);
    }

    /**
     * IO异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(IOException.class)
    @ResponseBody
    public ResponseEntity<?> doHandleIOException(IOException ex) {
        Result error = new Result();
        // 异常
        error.setCode(BusinessStatus.UNKNOWN.getCode());
        error.setMsg(ex.getMessage());
        log.warn("[空指针异常] 业务编码：{} 异常记录：{}", error.getCode(), error.getMsg());
        ex.printStackTrace();
        return new ResponseEntity<>(error, HttpStatus.OK);
    }

    /**
     * 运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result doHandleRuntimeException(RuntimeException e) {
        e.printStackTrace();//控制台
        log.error(e.getMessage());
        return Result.fail(BusinessStatus.FAIL, e.getMessage());
    }


}